/**
 * cloneable接口和深拷贝
 */
package demo2;
class Money implements Cloneable {
    public double money = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable {
    public String name;
    public Money m;
    public Person(String name) {
        this.name = name;
        m = new Money();
    }

    /**
     * 浅拷贝
     * @return
     * @throws CloneNotSupportedException
     * 只调用父类方法,编译器直接生成
     */
//    @Override
//    protected Object clone() throws CloneNotSupportedException {
//        return super.clone();
//    }

    /**
     * 深拷贝
     * @return
     * @throws CloneNotSupportedException
     * 对原对象内部进行实现,使其独立于原对象
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person)super.clone();//clone对象
        tmp.m = (Money)this.m.clone();
        return tmp;
    }
}
public class Test2 {
    public static void main(String[] args) throws CloneNotSupportedException {
        /**
         * 深拷贝: 拷贝一份原对象数据,独立于原对象,两者不存在任何关系,需要程序员进行实现
         * 浅拷贝:拷贝一份原对象数据,两者可能会存在联系
         */
        Person person1 = new Person("zhangSan");
        Person person2 = (Person)person1.clone();

        System.out.println("person1拷贝前" + person1.m.money);
        System.out.println("person2拷贝前" + person2.m.money);

        person2.m.money = 99.99;

        System.out.println("person1拷贝后" + person1.m.money);
        System.out.println("person2拷贝后" + person2.m.money);


    }
    /**
     * 实现clone拷贝
     * @param args
     * @throws
     *      1.重写Object clone方法使用super进行访问父类方法
     *      2.向下转型
     *      3.throws异常
     */
    public static void main1(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person("zhangSan");

        Person person2 = (Person)person1.clone();

        System.out.println(person2.name);
    }
}
